package top.haijunit.work.modules.access.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.haijunit.work.modules.access.domain.PermissionRelationInfo;
import top.haijunit.work.modules.access.entity.PermissionRelationEntity;
import top.haijunit.work.modules.access.mapper.PermissionRelationMapper;

import java.util.List;

/**
 * 权限关系服务
 *
 * @author zhanghaijun
 * @since 2024-08-30
 */
@Slf4j
@Service
public class PermissionRelationService extends ServiceImpl<PermissionRelationMapper, PermissionRelationEntity> {


    /**
     * 更新权限之间的关系
     *
     * @param uniqCode 权限编码
     * @param repelList  互斥的权限关系
     * @param dependList 依赖的权限关系
     */
    public void updatePermissionRelation(Long code, List<PermissionRelationInfo.RelationInfo> repelList, List<PermissionRelationInfo.RelationInfo> dependList) {
        deletePermissionRelation(code);
        if (repelList != null && !repelList.isEmpty()) {
            repelList.stream().distinct().forEach(item -> {
                PermissionRelationEntity entity = new PermissionRelationEntity();
                entity.setPermissionCode(code);
                entity.setRelationType(1);
                entity.setRelationPermissionCode(item.getPermissionCode());
                entity.setRemarks(item.getRemarks());
                baseMapper.insert(entity);
            });
        }
        if (dependList != null && !dependList.isEmpty()) {
            dependList.stream().distinct().forEach(item -> {
                PermissionRelationEntity entity = new PermissionRelationEntity();
                entity.setPermissionCode(code);
                entity.setRelationType(2);
                entity.setRelationPermissionCode(item.getPermissionCode());
                entity.setRemarks(item.getRemarks());
                baseMapper.insert(entity);
            });
        }
    }

    /**
     * 删除权限之间的关系
     *
     * @param code 权限编码
     */
    public void deletePermissionRelation(Long code) {
        LambdaQueryWrapper<PermissionRelationEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PermissionRelationEntity::getUniqCode, code);
        queryWrapper.or().eq(PermissionRelationEntity::getRelationPermissionCode, code);
        baseMapper.delete(queryWrapper);
    }
}
